<template>
  <div class="search-history" @touchmove.prevent>
    <van-cell 
      icon="underway-o" 
      title="历史搜索" 
      size="large" 
    >
      <template #right-icon>
        <van-icon name="delete-o" class="delete-icon" @click="onClear" />
      </template>
    </van-cell>
    <div class="history-tags">
      <van-tag 
        v-for="word in words"
        :key="word" 
        size="large" 
        color="#aaaaaa" 
        @click="onSearch(word)"
      >{{ word }}</van-tag>
    </div>
  </div>
</template>

<script>
// 搜索历史
import { getStorageItem, setStorageItem, removeStorageItem} from '@/utils/storage'

const key = 'searchWord'
const len = 20

export default {
  name: 'SearchHistory',
  data() {
    return {
      words: [], // 历史记录
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.words = this.getWords()
    })
  },
  methods: {
    // 搜索
    onSearch(word) {
      this.$emit('search', word)
    },
    // 获取缓存
    getWords() {
      return getStorageItem(key) || []
    },
    // 设置缓存
    setWord(word) {
      if (!word.replace(/\s+/g, '')) return
      const words = this.getWords()
      const has = words.includes(word)
      if (!has) {
        const length = words.length
        if (length >= len) {
          words.pop()
        }
        words.unshift(word)
        setStorageItem(key, words)

        this.words = words
      }
    },
    onClear() {
      this.$dialog.confirm({
        message: '清空历史搜索记录？',
        theme: 'round-button',
      }).then(() => {
        this.words = []
        removeStorageItem(key)
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.search-history {
  background-color: #fff;
  .delete-icon {
    font-size: 18px;
    line-height: inherit;
    padding-left: 10px;
  }
  .history-tags {
    padding: 10px 16px;
    .van-tag {
      margin-right: 10px;
      margin-bottom: 5px;
    }
  }
}
</style>
